import axios from 'axios';
import type { Agent } from './GitHubService';

// API基础URL
const API_BASE_URL = '/api/mcpTool';

/**
 * MCP API服务，用于与后端API交互
 */
export function useMcpApiService() {
  /**
   * 获取所有项目
   */
  const getAllProjects = async (): Promise<Agent[]> => {
    try {
      // 从本地缓存获取
      const stored = localStorage.getItem('mcp_projects');
      if (stored) {
        return JSON.parse(stored);
      }
      
      // 从API获取
      const response = await axios.get(`${API_BASE_URL}/projects`);
      const projects = response.data;
      
      // 保存到本地缓存
      localStorage.setItem('mcp_projects', JSON.stringify(projects));
      
      return projects;
    } catch (error) {
      console.error('获取所有项目出错:', error);
      // 返回空数组作为降级处理
      return [];
    }
  };

  /**
   * 按ID获取项目
   */
  const getProjectById = async (id: string): Promise<Agent | undefined> => {
    try {
      const response = await axios.get(`${API_BASE_URL}/project/${id}`);
      return response.data;
    } catch (error) {
      console.error(`获取项目ID=${id}出错:`, error);
      return undefined;
    }
  };

  /**
   * 删除项目
   */
  const deleteProject = async (id: string): Promise<void> => {
    try {
      await axios.delete(`${API_BASE_URL}/project/${id}`);
      // 更新本地缓存
      const projects = await getAllProjects();
      const updatedProjects = projects.filter(proj => proj.id !== id);
      localStorage.setItem('mcp_projects', JSON.stringify(updatedProjects));
    } catch (error) {
      console.error(`删除项目ID=${id}时出错:`, error);
      throw error;
    }
  };

  /**
   * 添加新项目
   */
  const addProject = async (project: Omit<Agent, 'id' | 'stars' | 'lastUpdated'>): Promise<Agent> => {
    try {
      const response = await axios.post(`${API_BASE_URL}/project`, project);
      
      // 更新本地缓存
      const projects = await getAllProjects();
      const updatedProjects = [...projects, response.data];
      localStorage.setItem('mcp_projects', JSON.stringify(updatedProjects));
      
      return response.data;
    } catch (error) {
      console.error('添加项目出错:', error);
      throw error;
    }
  };

  /**
   * 搜索GitHub仓库，返回仓库信息对象数组
   */
  const searchGitHubRepositories = async (query: string, token?: string): Promise<Agent[]> => {
    try {
      if (!query) return [];
      const params = new URLSearchParams();
      params.append('q', query);
      if (token) params.append('token', token);
      const response = await axios.get(`${API_BASE_URL}/search?${params.toString()}`);
      return response.data as Agent[];
    } catch (error) {
      console.error('搜索GitHub仓库出错:', error);
      return [];
    }
  };

  /**
   * 刷新代理数据
   */
  const refreshAgentData = async (): Promise<Agent[]> => {
    try {
      // 清除本地缓存
      localStorage.removeItem('mcp_projects');
      
      // 调用刷新API
      const response = await axios.post(`${API_BASE_URL}/refresh`);
      const projects = response.data;
      
      // 更新本地缓存
      localStorage.setItem('mcp_projects', JSON.stringify(projects));
      
      return projects;
    } catch (error) {
      console.error('刷新代理数据出错:', error);
      return [];
    }
  };

  /**
   * 从GitHub URL提取仓库名和所有者
   */
  const parseGitHubUrl = (url: string): { owner: string, repo: string } | null => {
    try {
      // 匹配GitHub URL格式
      const match = url.match(/github\.com\/([^\/]+)\/([^\/]+)/);
      if (match && match.length >= 3) {
        return {
          owner: match[1],
          repo: match[2].replace(/\.git$/, '') // 移除可能的.git后缀
        };
      }
      return null;
    } catch (error) {
      console.error('解析GitHub URL出错:', error);
      return null;
    }
  };

  /**
   * 检查文本中是否包含AI代理或MCP相关关键词
   */
  const containsAgentKeywords = (text: string): boolean => {
    if (!text) return false;
    
    const keywords = [
      'ai agent', 'ai-agent', 'aiagent',
      'llm agent', 'llm-agent',
      'autonomous agent', 'autonomous-agent',
      'agent framework', 'agent-framework',
      'multi-agent', 'multiagent',
      'agent orchestration', 'agent-orchestration',
      'mcp', 'multi-agent collaboration protocol',
      'agent communication'
    ];
    
    const lowercaseText = text.toLowerCase();
    return keywords.some(keyword => lowercaseText.includes(keyword));
  };

  /**
   * 批量添加项目对象列表
   */
  const addProjects = async (projectsData: Agent[]): Promise<Agent[]> => {
    try {
      if (!projectsData || projectsData.length === 0) {
        return [];
      }
      const response = await axios.post(`${API_BASE_URL}/projects/batch`, projectsData);
      const newProjects = response.data as Agent[];
      // 更新本地缓存
      if (newProjects.length > 0) {
        const projects = await getAllProjects();
        const updatedProjects = [...projects, ...newProjects];
        localStorage.setItem('mcp_projects', JSON.stringify(updatedProjects));
      }
      return newProjects;
    } catch (error) {
      console.error('批量添加项目出错:', error);
      throw error;
    }
  };

  return {
    getAllProjects,
    getProjectById,
    addProject,
    addProjects,
    searchGitHubRepositories,
    refreshAgentData,
    parseGitHubUrl,
    containsAgentKeywords,
    deleteProject
  };
}